import { Form, Input, InputNumber, message, Modal, Select } from "antd"
import { forwardRef, useImperativeHandle, useState } from "react"
import { useLoaderData } from "react-router"
import { userAddApi } from "../../../api/welcome/user"

const { useForm } = Form

export type UserFormRef = {
  openModal: () => void
}

type FieldType = {
  account: string
  role: number
  name: string
  age: number
  gender: number
}

const UserForm = forwardRef<UserFormRef, {}>((_, ref) => {
  const [open, setOpen] = useState<boolean>(false)
  const [loading, setLoading] = useState<boolean>(false)
  const [form] = useForm()
  const user = useLoaderData()
  useImperativeHandle(ref, () => ({
    openModal: openModal
  }));


  const openModal = () => {
    if (!loading) {
      setOpen(old => !old)
    }
  }

  const onOk = async () => {
    form.validateFields().then(async (value: any) => {
      setLoading(true)
      const res = await userAddApi({ ...value, password: value?.account })
      if (res?.code == 200) {
        message.success("添加成功")
      }
      openModal()
      setLoading(false)
    })
  }

  return <Modal
    title="添加用户"
    open={open}
    onOk={onOk}
    loading={loading}
    onCancel={openModal}
    afterClose={() => form.resetFields()}
    maskClosable={false}
    classNames={{
      body: 'max-h-[480px] overflow-auto'
    }}
  >
    <Form
      name="userForm"
      form={form}
      layout="vertical"
    >
      <Form.Item<FieldType>
        label="账号"
        name="account"
        rules={[{ required: true, message: '请输入账号' }]}
      >
        <Input placeholder="请输入账号" allowClear />
      </Form.Item>
      <Form.Item<FieldType>
        label="姓名"
        name="name"
      >
        <Input placeholder="请输入姓名" allowClear />
      </Form.Item>
      <Form.Item<FieldType>
        label="角色"
        name="role"
        rules={[{ required: true, message: '请选择角色' }]}
      >
        <Select
          placeholder="请选择角色"
          allowClear
          options={
            user?.role == 0 ? [{ label: "管理员", value: 1 }, { label: "普通用户", value: 2 }] : [{ label: "用户", value: 2 }]
          } />
      </Form.Item>
      <Form.Item<FieldType>
        label="年龄"
        name="age"
      >
        <InputNumber className="!w-full" placeholder="请输入年龄" min={0} max={100} />
      </Form.Item>
      <Form.Item<FieldType>
        label="性别"
        name="gender"
      >
        <Select placeholder="请选择性别" allowClear options={[
          { label: '女', value: 0 },
          { label: '男', value: 1 }
        ]} />
      </Form.Item>
    </Form>
  </Modal>

})

export default UserForm